<?php
import("com.yado.drivers.ITable");
class Table implements ITable {
	/**
	 * Enter description here...
	 *
	 * @var IConnection
	 */
	private $_connection;
	private $_vars;
	/**
	 * Enter description here...
	 *
	 * @var TableDescriptor
	 */
	private $_descriptor;
	public function getDescriptor(){
		return $this->_descriptor;
	}
	private $_id;
	private $_pkField;
	public function getPkName(){
		return $this->_pkField->getName();	
	}
	public function __construct(TableDescriptor $descriptor){
		$this->_descriptor = $descriptor;
		$this->_connection = $descriptor->getConnection();
		$fields = $this->_vars = $this->_descriptor->getFields();
		foreach ($fields as $field) {
			if ($field->isPrimary()){
				$this->_pkField = $field;
			}
			$this->_vars[$field->getName()]=$field;
		}
	}
	
	public function init($pk){
		$sql = "SELECT * FROM ".$this->_descriptor->getName()." WHERE ".$this->_pkField->getName()."=".$pk.";";
		$stmt = $this->_connection->prepearStatement($sql);
		$stmt->execute();
		$res = $stmt->getResultSet();
		$fields = $res->next();
		foreach ($fields as $fieldName=>$field){
			$this->_vars[$fieldName]->setValue($field);
		} 
		return $this;
	}
	
	public function save(){
		$sql = "INSERT INTO ".$this->_descriptor->getName()." SET ";
		foreach ($this->_vars as $key=>$value) {
			$sql.=$key."='".$value."'";
		}
		$sql.=";";
		$stmt=$this->_connection->prepearStatement($sql);
		$stmt->execute();
	}
	
	public function __get($name){
		if(isset($this->_vars[$name])){
			return $this->_vars[$name];
		} return null;
	}
	
	public function __set($name,$value){
		if (isset($this->_vars[$name])){
			$this->_vars[$name]->setValue($value);
		}
	}
}

?>